package com.ovopark.organize.server.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ovopark.organize.server.mapper.FranchiseesRegistrationAddressMapper;
import com.ovopark.organize.server.model.entity.FranchiseesRegistrationAddress;
import com.ovopark.organize.server.model.query.FranchiseesAddressQuery;
import com.ovopark.organize.server.model.vo.FranchiseesRegistrationAddressVo;
import com.ovopark.organize.server.model.vo.IndustryVo;
import com.ovopark.organize.server.service.CategoryService;
import com.ovopark.organize.server.service.FranchiseesRegistrationAddressService;
import com.ovopark.organize.server.util.CollectionUtil;
import com.ovopark.organize.server.util.HttpUtils;
import com.ovopark.organize.server.util.ThreadPoolTaskUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;


@Service
public class FranchiseesRegistrationAddressServiceImpl extends ServiceImpl<FranchiseesRegistrationAddressMapper, FranchiseesRegistrationAddress> implements FranchiseesRegistrationAddressService {
    Logger logger = LoggerFactory.getLogger(FranchiseesRegistrationAddressServiceImpl.class);
    @Resource
    private FranchiseesRegistrationAddressMapper baseMapper;
    @Value("${myConfig.franchiseesReportUrl}")
    private String franchiseesReportUrl;
    @Resource
    private CategoryService categoryService;

    
    private String getReportUrl = "/api/v1/map/master/insertAmapRecord";


    @Override
    public FranchiseesRegistrationAddress saveOrUpdateFranchiseesAddress(FranchiseesRegistrationAddress vo) {
        Boolean isRequestReport = false;
        if(vo.getId() !=null){
         // 获取 之前的 经纬度 判断 是否需要 重新调 选址项目id
            FranchiseesRegistrationAddress oldAddress =  getAddressById(vo.getId());
            String oldLa = oldAddress.getLatitude() + ","+oldAddress.getLongitude();
            String newLa = vo.getLatitude()+","+vo.getLongitude();
            if(!oldLa.equals(newLa) && vo.getLatitude() !=null && vo.getLongitude() !=null){
                // 经纬度发生变化 重新调 报告id
                isRequestReport = true;
                vo.setReportId(null);
            }
        }else if(vo.getLatitude() !=null && vo.getLongitude() !=null){
            // 调报告id
            isRequestReport = true;

        }
       vo =  saveOrUpdateAddress(vo);
        if(isRequestReport){
            Integer reportId = getReportId(vo.getId(),vo.getGroupId(),vo.getLatitude(),vo.getLongitude());
            if(reportId !=null){
                vo.setReportId(reportId);
            }
        }

        return vo;
    }


    @Override
    public  Integer getReportId(Integer addressId,Integer groupId,Double latitude,Double longitude){
        final Integer[] id = {null};
        if(StringUtils.isNotEmpty(franchiseesReportUrl)){
            // 先获取 crm 下面 的 企业行业
            List<Integer> groupIds = new ArrayList<>();
            groupIds.add(groupId);
            ThreadPoolTaskUtils.getThreadPool().execute(new Runnable() {
                @Override
                public void run() {
                    List<IndustryVo> industryVos =  categoryService.getCategoryByCrm(groupIds);
                    if(CollectionUtil.isNotEmpty(industryVos)){
                        IndustryVo industryVo = industryVos.get(0);
                        String industryPath = industryVo.getFullIndustryPath();
                        if(StringUtils.isNotEmpty(industryPath)){
                            List<String> industryPathList = Arrays.asList(industryPath.split(">"));
                            Map<String, Object> params = new HashMap<>();
                            params.put("lon",longitude);
                            params.put("lat",latitude);

                            for (int i = 0; i <industryPathList.size() ; i++) {
                                if(i ==0){
                                    params.put("industryFirst",industryPathList.get(i));
                                }else if(i ==1){
                                    params.put("industrySecond",industryPathList.get(i));
                                }else {
                                    params.put("industryThird",industryPathList.get(i));
                                }
                            }

                            try {

                                String url = franchiseesReportUrl+getReportUrl;
                                String result =   HttpUtils.doPostWithExtraHeaders(url,null,params,30000);
                                logger.info("result=="+result+"url=="+url+"params=="+params+"addressId:"+addressId);
                                JSONObject object = JSON.parseObject(result);
                                Integer code = object.getIntValue("code");
                                if(code ==200 && object.get("data") !=null){
                                    id[0] = object.getInteger("data");
                                    FranchiseesRegistrationAddress address = getAddressById(addressId);
                                    address.setReportId(id[0]);
                                    saveOrUpdateAddress(address);
                                }else {
                                    logger.info("getReportId:"+params+"addressId:"+addressId+"result:"+result);
                                }

                            }catch (Exception e){
                                logger.info("getReportId:"+params+"addressId:"+addressId+"error:"+e);
                            }

                        }


                    }

                }
            });





        }

       return id[0];

    }

    @Override
    public List<FranchiseesRegistrationAddress> getAddressByIds(Integer groupId,List<Integer> ids) {
        LambdaQueryWrapper<FranchiseesRegistrationAddress> queryWrapper = new LambdaQueryWrapper<>();
        if(groupId !=null){
            queryWrapper.eq(FranchiseesRegistrationAddress::getGroupId,groupId);
        }
        queryWrapper.in(FranchiseesRegistrationAddress::getId,ids);
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public void deleteAddressByIdList(List<Integer> ids) {
        baseMapper.deleteBatchIds(ids);
    }

    @Override
    public void updateNameByFranchiseesId(Integer franchiseesId, String name, String mobilePhone) {
        if(StringUtils.isNotEmpty(name) && StringUtils.isNotEmpty(mobilePhone)){
            baseMapper.updateNameByFranchiseesId(franchiseesId,name,mobilePhone);
        }

    }


    @Override
    public FranchiseesRegistrationAddress saveOrUpdateAddress(FranchiseesRegistrationAddress vo) {
        if(vo.getId() !=null){
            baseMapper.updateById(vo);
        }else {
            baseMapper.insert(vo);
        }
        return vo;
    }

    @Override
    public IPage<FranchiseesRegistrationAddressVo> getFranchiseesAddressPage(Page<FranchiseesRegistrationAddress> page, Integer groupId, FranchiseesAddressQuery query) {

        IPage<FranchiseesRegistrationAddressVo> list = baseMapper.getFranchiseesAddressPage(page,groupId,query);

        return list;
    }

    @Override
    public FranchiseesRegistrationAddress getAddressById(Integer id) {
        return baseMapper.selectById(id);
    }

    @Override
    public void deleteAddressById(Integer id) {
        baseMapper.deleteById(id);
    }


}
